package jsyf.oa.service.wreport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.dao.wreport.WReportUnfinishDao;
import jsyf.oa.dao.wreport.WReportUnfinishMainDao;
import jsyf.oa.dao.wreport.WReportUnfinishPersonDao;
import jsyf.oa.dao.wreport.WReportUnfinishReplyDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.wreport.*;
import jsyf.oa.facade.wreport.WReportUnfinishFacade;
import jsyf.oa.service.attach.AttachModuleService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by WHH-PC on 2018/1/15.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WReportUnfinishService implements WReportUnfinishFacade {

    @Autowired
    WReportUnfinishMainDao wReportUnfinishMainDao;
    @Autowired
    WReportUnfinishDao wReportUnfinishDao;
    @Autowired
    WReportUnfinishPersonDao wReportUnfinishPersonDao;
    @Autowired
    WReportUnfinishReplyDao wReportUnfinishReplyDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private AttachModuleDao attachDao;

    @Override
    public String saveUnfinishMain(String jsonData) {
        StringBuilder sbReceiverIds = new StringBuilder();

        JSONObject obj = JSON.parseObject(jsonData);
        String id = obj.getString("id");
        String checked = obj.getString("checked");
        String userId = obj.getString("userId");
        String userName = obj.getString("userName");
        String trackTitle = obj.getString("trackTitle");

        JSONArray principalArray = obj.getJSONArray("principal");
        JSONArray csrArray = JSON.parseArray(obj.getString("csrPerson"));
        JSONArray cyrArray = JSON.parseArray(obj.getString("cyrPerson"));

        String principalId = "";
        if (principalArray.size() > 0) {
            principalId = JSON.parseObject(principalArray.get(0).toString()).getString("id");
            sbReceiverIds.append(principalId).append("|");
        }

        WReportUnfinishMainEntity wReportUnfinishMainEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportUnfinishMainEntity.class);
        wReportUnfinishMainEntity.setPrincipal(principalId);
        wReportUnfinishMainEntity.setType("3");
        wReportUnfinishMainEntity.setJobState("0");
        wReportUnfinishMainEntity.setJinzhan(wReportUnfinishMainEntity.getTrackContent());
        if (id.isEmpty()) {
            wReportUnfinishMainDao.add(wReportUnfinishMainEntity);
            id = wReportUnfinishMainEntity.getId();
        } else {
            wReportUnfinishMainEntity.setId(id);
            wReportUnfinishMainDao.update(wReportUnfinishMainEntity);
        }

        wReportUnfinishPersonDao.delete("delete from T_WRT_UNFINISH_PERSON where MAIN_ID=? ", new String[]{id});
        for (Object object : csrArray) {
            JSONObject jsonObject = (JSONObject) object;
            String personId = jsonObject.getString("id");
            WReportUnfinishPersonEntity wReportUnfinishPersonEntity = new WReportUnfinishPersonEntity();
            wReportUnfinishPersonEntity.setMainId(id);
            wReportUnfinishPersonEntity.setPersonId(personId);
            wReportUnfinishPersonEntity.setPersonType(2);
            wReportUnfinishPersonDao.add(wReportUnfinishPersonEntity);
            if (checked.toLowerCase().equals("true"))
                sbReceiverIds.append(personId).append("|");
        }
        for (Object object : cyrArray) {
            JSONObject jsonObject = (JSONObject) object;
            String personId = jsonObject.getString("id");
            WReportUnfinishPersonEntity wReportUnfinishPersonEntity = new WReportUnfinishPersonEntity();
            wReportUnfinishPersonEntity.setMainId(id);
            wReportUnfinishPersonEntity.setPersonId(personId);
            wReportUnfinishPersonEntity.setPersonType(1);
            wReportUnfinishPersonDao.add(wReportUnfinishPersonEntity);
            sbReceiverIds.append(personId).append("|");
        }

        //保存附件
        //删除
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{id});
        //添加
        List<JSONObject> jsonObjectList = (List<JSONObject>) obj.get("attaches");
        for (JSONObject jsonObject : jsonObjectList) {
            String attAchesId = jsonObject.get("id").toString();
            AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
            attachModuleEntity.setAttachId(attAchesId);
            attachModuleEntity.setAttachModule(17);
            attachModuleEntity.setModuleId(id);
            attachModuleDao.add(attachModuleEntity);
            attachModuleDao.addAttach(attAchesId);
        }

        //发送消息
        List<JSONObject> userList = wReportUnfinishPersonDao.getUserListByIds(sbReceiverIds.toString().replace(userId + "|", "").replace(userId, ""));
        for (JSONObject jsonObject : userList) {
            String uName = jsonObject.get("NAME").toString();
            String uId = jsonObject.get("ID").toString();

            //微信通知
            StringBuilder sbMsg = new StringBuilder();
            sbMsg.append(uName + "，你好！\n");
            sbMsg.append(userName + "发起未关闭事项，主题为“");
            sbMsg.append(trackTitle.length() > 25 ? trackTitle.substring(0, 25) + "..." : trackTitle);
            sbMsg.append("”，请注意查收！！");

            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", uId);
            msgObject.put("content", sbMsg.toString());
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }

        return id;
    }

    @Override
    public String save(String jsonData) {
        WReportUnfinishMainEntity wReportUnfinishMainEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportUnfinishMainEntity.class);
        //添加主表
        wReportUnfinishMainDao.add(wReportUnfinishMainEntity);
        String mainId = wReportUnfinishMainEntity.getId();
        //添加子表
        WReportUnfinishEntity wReportUnfinishEntity = new WReportUnfinishEntity();
        wReportUnfinishEntity.setMainId(mainId);
        wReportUnfinishEntity.setwId("");
        wReportUnfinishEntity.setJinzhan(wReportUnfinishMainEntity.getJinzhan());
        wReportUnfinishEntity.setJobState(wReportUnfinishMainEntity.getJobState());
        wReportUnfinishEntity.setOverTime(wReportUnfinishMainEntity.getOverTime());
        wReportUnfinishEntity.setUserId(wReportUnfinishMainEntity.getUserId());
        wReportUnfinishEntity.setTrackContent(wReportUnfinishMainEntity.getTrackContent());
        wReportUnfinishEntity.setType(wReportUnfinishMainEntity.getType());
        wReportUnfinishDao.add(wReportUnfinishEntity);
        return mainId;
    }

    @Override
    public List<JSONObject> getWReportUnfinishCount() {
        return wReportUnfinishMainDao.getWReportUnfinishCount();
    }

    @Override
    public JSONObject getWReportUnfinishMainList(JSONObject obj) {
        Integer pageSize = 30;
        Integer pageIndex = Integer.parseInt(obj.getString("requestPage") == null ? "1" : obj.getString("requestPage"));
        String keyWord = obj.getString("keyWord");
        String userId = obj.getString("userId");
        String selectedCompanyId = obj.getString("selectedCompanyId");

        StringBuilder sbConditon = new StringBuilder();
        String condition = "";
        if (keyWord != null && !keyWord.isEmpty()) {
            sbConditon.append("AND (");
            sbConditon.append("TRACK_CONTENT LIKE '%" + keyWord + "%' ");
            sbConditon.append("OR TRACK_TITLE LIKE '%" + keyWord + "%'");
            sbConditon.append(")");
        }
        if (StringUtils.isNotEmpty(selectedCompanyId)) {
            sbConditon.append(" AND D.companyId='" + selectedCompanyId + "'");
        }
        sbConditon.append("AND( ");
        sbConditon.append("PRINCIPAL='" + userId + "' ");
        sbConditon.append("OR USER_ID = '" + userId + "' ");
        sbConditon.append("OR A.ID IN (SELECT MAIN_ID FROM T_WRT_UNFINISH_PERSON WHERE PERSON_ID ='" + userId + "' ) ");
        sbConditon.append(") ");

        condition = sbConditon.toString();
        sbConditon.append("order by create_time desc ");

        sbConditon.append("Limit ");
        sbConditon.append((pageIndex - 1) * pageSize);
        sbConditon.append(",");
        sbConditon.append(pageSize);

        List<JSONObject> list = wReportUnfinishMainDao.getWReportUnfinishMainList(sbConditon.toString());
        setPersonAndTrack(list);
        getAttachment(list);
        Integer recordCount = wReportUnfinishMainDao.getWReportUnfinishMainListCount(condition);

        JSONObject objResult = new JSONObject();
        objResult.put("records", list);

        JSONObject sendData = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageIndex", pageIndex);
        sendData.put("pageCount", (int) Math.ceil((double) recordCount / pageSize));
        objResult.put("pager", sendData);

        return objResult;
    }

    /**
     * 获取附件
     *
     * @param list
     */
    private void getAttachment(List<JSONObject> list) {
        if (list.size() == 0)
            return;
        StringBuilder sbSql = new StringBuilder();
        sbSql.append("and moduleId in (");
        for (JSONObject jsonObject : list) {
            sbSql.append("'").append(jsonObject.get("ID").toString()).append("',");
        }
        sbSql.setLength(sbSql.length() - 1);
        sbSql.append(") ");
        List<JSONObject> jsonObjectList = attachDao.getByCondition(sbSql.toString(), null);

        Map<String, List<JSONObject>> map = new HashedMap();
        for (JSONObject jsonObject : jsonObjectList) {
            String moduleId = jsonObject.get("moduleId").toString();

            if (map.containsKey(moduleId)) {
                map.get(moduleId).add(jsonObject);
            } else {
                List<JSONObject> objectList = new ArrayList<>();
                objectList.add(jsonObject);
                map.put(moduleId, objectList);
            }
        }

        for (JSONObject item : list) {
            String id = item.get("ID").toString();
            if (map.containsKey(id))
                item.put("attaches", map.get(id));
            else {
                item.put("attaches", new ArrayList<>());
            }
        }
    }

    /**
     * 设置参与人和抄送人
     *
     * @param list
     */
    private void setPersonAndTrack(List<JSONObject> list) {
        if (list.size() == 0)
            return;

        StringBuffer sbMainIds = new StringBuffer();
        Map<String, String> map = new HashMap<>();
        Map<String, List<JSONObject>> mapTrack = new HashMap<>();
        int i = 1;
        for (JSONObject jsonObject : list) {
            jsonObject.put("sn", i);
            i++;
            sbMainIds.append("'").append(jsonObject.get("ID")).append("',");
        }

        String strMainIds = sbMainIds.length() > 0 ? sbMainIds.toString().substring(0, sbMainIds.toString().length() - 1) : sbMainIds.toString();

        List<JSONObject> personList = wReportUnfinishPersonDao.getPersonList(strMainIds);

        for (JSONObject jsonObject : personList) {
            String mainId = jsonObject.getString("MAIN_ID");
            String personId = jsonObject.getString("PERSON_ID");
            String userName = jsonObject.getString("USER_NAME");
            String personType = jsonObject.getString("PERSON_TYPE");

            String mapUserIdKey = mainId + "_" + personType;
            String mapUserIds = map.get(mapUserIdKey);
            map.put(mapUserIdKey, mapUserIds == null ? personId : mapUserIds + ";" + personId);

            String mapUserNameKey = mainId + "_" + personType + "_name";
            String mapUserNames = map.get(mapUserNameKey);
            map.put(mapUserNameKey, mapUserNames == null ? userName : mapUserNames + "/" + userName);
        }

        //跟踪记录
        List<JSONObject> trackList = wReportUnfinishDao.getTrackList(strMainIds);
        for (JSONObject jsonObject : trackList) {
            jsonObject.put("replayList", "");
            jsonObject.put("btnReply", 0);
            String mainId = jsonObject.getString("MAIN_ID");
            if (mapTrack.containsKey(mainId))
                mapTrack.get(mainId).add(jsonObject);
            else {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                jsonObjectList.add(jsonObject);
                mapTrack.put(mainId, jsonObjectList);
            }
        }

        //添加跟踪记录、抄送人、参与人
        for (JSONObject jsonObject : list) {
            String mainId = jsonObject.getString("ID");
            jsonObject.put("cyr", map.get(mainId + "_1"));
            jsonObject.put("csr", map.get(mainId + "_2"));
            jsonObject.put("cyrName", map.get(mainId + "_1_name"));
            jsonObject.put("csrName", map.get(mainId + "_2_name"));
            jsonObject.put("trackList", mapTrack.containsKey(mainId) ? mapTrack.get(mainId) : "");
        }

    }

    @Override
    public List<JSONObject> getWReportUnfinishListByMainId(JSONObject obj) {
        String mainId = obj.getString("mainId");
        return wReportUnfinishMainDao.getWReportUnfinishListByMainId(mainId);
    }

    @Override
    public List<JSONObject> getWReportUnfinishViewListByPage(JSONObject obj) {
        List<JSONObject> list = wReportUnfinishDao.getUnfinishViewListByPage("", null);
        return list;
    }

    @Override
    public String overWReportUnfinishMain(String jsonData) {
        WReportUnfinishMainEntity wReportUnfinishMainEntity = JSON.toJavaObject(JSON.parseObject(jsonData), WReportUnfinishMainEntity.class);
        wReportUnfinishMainEntity.setJobState("1");
        String overTime = DateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
        wReportUnfinishMainEntity.setOverTime(overTime);
        int row = wReportUnfinishMainDao.update(wReportUnfinishMainEntity);
        return wReportUnfinishMainEntity.getId();

    }

    @Override
    public List<JSONObject> getWReportUnfinishReply(String trackId) {
        return wReportUnfinishReplyDao.getTrackReplyList(trackId);
    }

    @Override
    public String addTrack(JSONObject obj) {
        String mainId = obj.getString("mainId");

        WReportUnfinishEntity wReportUnfinishEntity = new WReportUnfinishEntity();
        wReportUnfinishEntity.setTrackContent(obj.getString("trackContent"));
        wReportUnfinishEntity.setUserId(obj.getString("userId"));
        wReportUnfinishEntity.setType("3");
        wReportUnfinishEntity.setMainId(mainId);
        wReportUnfinishDao.add(wReportUnfinishEntity);

        sendReplyMsgToWX(obj);
        return wReportUnfinishEntity.getId();
    }

    /**
     * 微信通知已回复
     *
     * @param obj
     */
    private void sendReplyMsgToWX(JSONObject obj) {
        String checked = obj.getString("checked");
        String userName = obj.getString("userName");
        String mainId = obj.getString("mainId");
        String principal = obj.getString("principal");//负责人
        String publisher = obj.getString("publisher");//发布人
        String trackTitle = obj.getString("trackTitle");
        String userId = obj.getString("userId");

        StringBuilder sbReceiverIds = new StringBuilder();
        //获取抄送人和参与人
        List<JSONObject> personList = wReportUnfinishPersonDao.getPersonList("'" + mainId + "'");
        for (JSONObject jsonObject : personList) {
            String personId = jsonObject.getString("PERSON_ID");
            String personType = jsonObject.getString("PERSON_TYPE");
            if (checked.equals("false") && personType.equals("2"))
                continue;
            sbReceiverIds.append(personId).append("|");
        }
        sbReceiverIds.append(principal).append("|").append(publisher);

        List<JSONObject> userList = wReportUnfinishPersonDao.getUserListByIds(sbReceiverIds.toString().replace(userId + "|", "").replace(userId, ""));
        for (JSONObject jsonObject : userList) {
            String uName = jsonObject.get("NAME").toString();
            String uId = jsonObject.get("ID").toString();
            StringBuilder sbMsg = new StringBuilder();

            sbMsg.append(uName + "，你好!\n");
            sbMsg.append(userName + "已回复主题为“");
            sbMsg.append(trackTitle);
            sbMsg.append("”的未关闭事项！");
            //微信通知
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", uId);

            msgObject.put("content", sbMsg.toString());
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }


    }

    @Override
    public String addReply(JSONObject obj) {
        WReportUnfinishReplyEntity wReportUnfinishReplyEntity = new WReportUnfinishReplyEntity();
        wReportUnfinishReplyEntity.setReplyContent(obj.getString("replyContent"));
        wReportUnfinishReplyEntity.setTrackId(obj.getString("trackId"));
        wReportUnfinishReplyEntity.setUserId(obj.getString("userId"));
        wReportUnfinishDao.add(wReportUnfinishReplyEntity);
        return wReportUnfinishReplyEntity.getId();
    }

    @Override
    public String closeMatter(JSONObject obj) {
        WReportUnfinishMainEntity wReportUnfinishMainEntity = new WReportUnfinishMainEntity();
        wReportUnfinishMainEntity.setJobState("1");
        wReportUnfinishMainEntity.setId(obj.getString("id"));
        wReportUnfinishDao.update(wReportUnfinishMainEntity);
        return wReportUnfinishMainEntity.getId();
    }

    @Override
    public List<JSONObject> getUnfinishPersonList() {
        List<JSONObject> jsonObjectList = wReportUnfinishMainDao.getUnfinishPersonList(DateUtils.formatDate(new Date(), "yyyy-MM-dd"));

        StringBuilder sbReceiverIds = new StringBuilder();
        int i = 0;
        for (JSONObject jsonObject : jsonObjectList) {
            String id = jsonObject.get("ID").toString();
            String userName = jsonObject.get("NAME").toString();
            sbReceiverIds.append(id);
            if (i != jsonObjectList.size() - 1)
                sbReceiverIds.append("|");
            i++;
        }
        List<JSONObject> userList = wReportUnfinishPersonDao.getUserListByIds(sbReceiverIds.toString());
        for (JSONObject jsonObject : userList) {
            String uName = jsonObject.get("NAME").toString();
            String uId = jsonObject.get("ID").toString();

            //微信通知
            StringBuilder sbMsg = new StringBuilder();
            sbMsg.append(uName + "，你好！\n");
            sbMsg.append("您有需要今天完成的未关闭事项，请悉知！！！");
            //微信通知
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", uId);
            msgObject.put("content", sbMsg.toString());
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }

        return jsonObjectList;
    }
}
